import { asyncRoutes, constantRoutes } from '@/router'
import Layout from '@/layout'

const state = {
  routes: [],
  addRoutes: []
}

const mutations = {
  SET_ROUTES: (state, routes) => {
    state.addRoutes = routes
    state.routes = constantRoutes.concat(routes)
  }
}

const actions = {
  generateRoutes({ commit }, {
    modules,
    menus
  }) {
    return new Promise(resolve => {
      const accessedRoutes = modules.map(module => {
        return {
          ...createModuleRoute(module),
          children: menus.filter(menu => menu.moduleId === module.moduleId)
            .map(menu => {
              return {
                ...createMenuRoute(menu)
              }
            })
        }
      })
      // commit('SET_ROUTES', accessedRoutes) // 后端配置路由
      // resolve(accessedRoutes)
      console.log(accessedRoutes)
      commit('SET_ROUTES', asyncRoutes) // 开发环境写死路由
      resolve(asyncRoutes)
    })
  }
}

function createModuleRoute(module) {
  return {
    path: module.moduleUrl,
    component: Layout,
    alwaysShow: true,
    name: getRouteName(module.moduleUrl),
    meta: {
      title: module.moduleName
    }
  }
}

function createMenuRoute(menu) {
  return {
    path: menu.menuUrl,
    component: loadView(menu.menuSrc),
    name: getRouteName(menu.menuUrl),
    meta: {
      title: menu.menuName
    }
  }
}

function getRouteName(url) {
  url = url.replace('/', '')
  return url.slice(0, 1).toUpperCase() + url.slice(1)
}

function loadView(view) {
  return (resolve) => require([`@/views${view}`], resolve)
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
